/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.classdiagram.editpart;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.draw2d.text.TextFlow;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.tools.CellEditorLocator;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.ElementImport;

import com.cea.papyrus.core.PapyrusMessages;
import com.cea.papyrus.core.PapyrusPlugin;
import com.cea.papyrus.core.directedit.FigureControler;
import com.cea.papyrus.core.directedit.ILabelControler;
import com.cea.papyrus.core.directedit.MultilineLabelDirectEditManager;
import com.cea.papyrus.core.directedit.PropertyAccessor;
import com.cea.papyrus.core.directedit.SimpleCellEditorLocator;
import com.cea.papyrus.core.directedit.TextFlowCellEditorLocator;
import com.cea.papyrus.core.editor.ModelManager;
import com.cea.papyrus.core.editor.mouseoveraction.ActionHandleManager;
import com.cea.papyrus.core.editpart.GraphNodeWithSemanticEditPart;
import com.cea.papyrus.core.figures.IconFigure;
import com.cea.papyrus.core.figures.NodeFigure;
import com.cea.papyrus.core.figures.NoteFigure;
import com.cea.papyrus.core.pseudoelement.GraphicalLink;
import com.cea.papyrus.core.ui.dialogs.PapyrusMessageDialog;
import com.cea.papyrus.core.utils.Debug;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;

/**
 * This is the controler of the {@link Comment}.
 * 
 * @author PT202707
 */
public class CommentEditPart extends GraphNodeWithSemanticEditPart {

	/**
	 * Manager for editing the comment.
	 */
	private DirectEditManager manager;

	/**
	 * Creates a new CommentEditPart.
	 * 
	 * @param modelManager 
	 * @param graphNode 
	 */
	public CommentEditPart(GraphNode graphNode,ModelManager modelManager) {
		super(graphNode,modelManager);
	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#createFigure()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	@Override
	protected IFigure createFigure() {
		// Force initialization of the manager when figure has changed
		manager = null;	
		//  Try to get figure from ContainerWithSemanticEditPart
		IFigure fig = super.createFigure();
		if (fig != null) {
			return fig;
		}
		return new NoteFigure();			
	}

	/*
	 * (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.ContainerEditPart#createEditPolicies()
	 */
	/**
	 * 
	 */
	@Override
	protected void createEditPolicies(){
		super.createEditPolicies();
		installActionHandle();
	}
	
	/**
	 * Install Action handles for this editPart.
	 * Use same toolEntries than in palette
	 */
	protected void installActionHandle() {
		// Install mouse hover
		ActionHandleManager actionMngr = new ActionHandleManager(this);	
		// Create a toolbar of actions.
		PaletteDrawer entries = new PaletteDrawer("creation tool");

		try{
			entries.add(PapyrusPlugin.creationToolFactory.getConnectionCreationToolEntry(
					PapyrusMessages.AddGraphicalLinkCommand_Description
					, PapyrusMessages.AddGraphicalLinkCommand_Label
					, GraphicalLink.class
					, null));

		}
		catch (Exception e) {
			PapyrusMessageDialog.display(e.getMessage(), e);
		}
		actionMngr.addTool(entries, PositionConstants.EAST, false, 5);

	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#refreshVisuals()
	 */
	/**
	 * 
	 */
	@Override
	protected void refreshVisuals() {
		Debug.debug(this, "refreshvisuals", channel);

		Dimension size = getGraphNode().getSize();
		Point p = getGraphNode().getPosition();
		Rectangle r = new Rectangle(p ,size);
		
		IFigure fig = getFigure();

		// if fig is a stereotype figure
		if (!(fig instanceof NoteFigure)) {
			IconFigure icf = (IconFigure) getFigure();
			icf.setName(getUmlElement().getBody());
		} else {
			org.eclipse.uml2.uml.Comment currentComment = getUmlElement();
			com.cea.papyrus.umlutils.Element currentElement = new com.cea.papyrus.umlutils.Element(getUmlElement());

			// Retrieve current class and figure
			NoteFigure f = (NoteFigure) fig; //get Class figure
			f.setComment(currentComment.getBody());//set the name of the primitive type

			// if fig is a ClassFigure
			((NodeFigure) fig).refreshColors(getGraphNode());
			// set additionnal graphical parameter
			f.setfigureFont(getGraphNode().getFontFamily());
			f.setFontSize((getGraphNode().getFontSize()));
			f.setLineThickness((getGraphNode().getLineThickness()));

			((NodeFigure) fig).refreshPresentation(getPresentation(), currentComment, getGraphNode());
			boolean hasIcon  = currentElement.hasIcon();
			boolean hasShape = currentElement.hasShape();
			//f.refreshStereotypes(currentElement.getStereotypes(), getPresentation(), hasIcon, hasShape);
			f.refreshStereotypes(f.stereotypesLabel(this), getPresentation(), hasIcon, hasShape);

		}

		((GraphicalEditPart) getParent()).setLayoutConstraint(
				this,
				fig,
				r);
	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#getUmlElement()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	public org.eclipse.uml2.uml.Comment getUmlElement() {
		Element e=((Uml1SemanticModelBridge)getGraphNode().getSemanticModel()).getElement();
		// case of element import
		if(e instanceof ElementImport){
			return (org.eclipse.uml2.uml.Comment)((ElementImport) e).getImportedElement();
		}
		// this is a simple Comment
		return (org.eclipse.uml2.uml.Comment)e;
	}
	
	/**
	 * Init the label direct edit manager.
	 * This method should be called when a Direct Edit request is performed.
	 */
	protected void initLabelEditManager() {
		if(manager==null) {
			// locator for the cell editor (on the name label)
			CellEditorLocator locator = null;
			final IFigure textFigure = getTextFigure();
			if(textFigure instanceof TextFlow) {
				locator = new TextFlowCellEditorLocator((TextFlow)textFigure);
			} else {
				locator = new SimpleCellEditorLocator(textFigure);
			}

			// defining how properties are modified in the model
			PropertyAccessor accessor = new PropertyAccessor() {
				public String getPropertyName() {
					return "Body";
				}
				
				public String getValue() {
					return getUmlElement().getBody();
				}
				public void setValue(String value) {
					getUmlElement().setBody(value);
				}
			};
			// defines the controler: link between model and view
			ILabelControler labelControler = new FigureControler(getTextFigure(), accessor);

			// creates the editing manager.
			manager = new MultilineLabelDirectEditManager(this, locator, labelControler);
		}
	}
	
	/**
	 * 
	 * 
	 * @return 
	 */
	protected IFigure getTextFigure() {
		IFigure fig = getFigure();
		
		if (fig instanceof IconFigure) {
			return (Label) fig;
		} else if (fig instanceof NoteFigure) {
			return ((NoteFigure) fig).getTextFigure();
		} else {
			Debug.error(this, "CommentEditPart::getTextFigure() : Unknown Figure type.", channel);
			return null;
		}
	}
	
	/**
	 * the direct edit mechanism requires the edit part to handle the direct edit
	 * request.
	 * 
	 * @param req the request that called the direct edit.
	 */
	public void performDirectEdit(Request req) {
		initLabelEditManager();
		manager.show();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.editparts.AbstractEditPart#performRequest(org.eclipse.gef.Request)
	 */
	/**
	 * 
	 * 
	 * @param request 
	 */
	@Override
	public void performRequest(Request request){
		if (RequestConstants.REQ_DIRECT_EDIT.equals(request.getType())) {
			performDirectEdit(request);
		}
	}

}
